package com.qdxwx.web.interceptor;


import com.qdxwx.data.service.user.UserService;
import com.qdxwx.models.user.User;
import com.qdxwx.web.utils.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

/**
 * 前台用户登录拦截器
 * @author developer
 */
public class AuthInterceptor implements HandlerInterceptor {

	@Autowired
	private UserService userService;

	@Override
	public boolean preHandle(HttpServletRequest request,
							 HttpServletResponse response, Object handler) throws Exception {
		User user = LoginUser.getUser(request);
		if (user == null) {
			user = userService.getByCookie(LoginUser.getCookie(request));
			if (user == null) {
				response.sendRedirect("/auth/login.html");//跳转登录页面 弹出登录框
				return false;
			}
			//仅更新用户活动时间
			userService.updateLoginTime(user.getUserId());
			LoginUser.setUser(request, user);
		}
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request,
						   HttpServletResponse response, Object handler,
						   ModelAndView modelAndView) throws Exception {

	}

	@Override
	public void afterCompletion(HttpServletRequest request,
								HttpServletResponse response, Object handler, Exception ex)
			throws Exception {

	}

}